const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const User = require('./User');
const Material = require('./Material');

const MaterialOrder = sequelize.define('materialOrder', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  orderNumber: {
    type: DataTypes.STRING(50),
    allowNull: false,
    unique: true
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: true, // 允许匿名购买
    references: {
      model: 'user',
      key: 'id'
    }
  },
  materialId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    references: {
      model: 'material',
      key: 'id'
    }
  },
  customerName: {
    type: DataTypes.STRING(100),
    allowNull: false
  },
  customerEmail: {
    type: DataTypes.STRING(100),
    allowNull: false
  },
  customerPhone: {
    type: DataTypes.STRING(20),
    allowNull: true
  },
  amount: {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: false
  },
  status: {
    type: DataTypes.ENUM('pending', 'processing', 'completed', 'failed', 'refunded'),
    defaultValue: 'pending'
  },
  ipAddress: {
    type: DataTypes.STRING(50),
    allowNull: true
  },
  notes: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  downloadToken: {
    type: DataTypes.STRING(100),
    allowNull: true
  },
  downloadTokenExpiry: {
    type: DataTypes.DATE,
    allowNull: true
  },
  downloadCount: {
    type: DataTypes.INTEGER,
    defaultValue: 0
  },
  maxDownloads: {
    type: DataTypes.INTEGER,
    defaultValue: 5 // 默认最多下载5次
  },
  createdAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  },
  updatedAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW
  }
}, {
  indexes: [
    {
      fields: ['orderNumber']
    },
    {
      fields: ['userId']
    },
    {
      fields: ['materialId']
    },
    {
      fields: ['status']
    },
    {
      fields: ['customerEmail']
    },
    {
      fields: ['downloadToken']
    }
  ]
});

// 同步模型到数据库
const syncMaterialOrder = async (force = false) => {
  try {
    await MaterialOrder.sync({ force });
    console.log('MaterialOrder 模型同步成功');
  } catch (error) {
    console.error('MaterialOrder 模型同步失败:', error);
  }
};

module.exports = {
  MaterialOrder,
  syncMaterialOrder
};